﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// 子弹管理器
/// TODO 添加子弹对象池
/// </summary>
public class BulletManager : MonoBehaviour {


    private static BulletManager instance = null;

    public GameObject emptyRoot;

    public GameObject normalBulletPrefab;

    private Dictionary<string, Queue<GameObject>> bulletPool;

	// Use this for initialization
	void Start () {
        bulletPool = new Dictionary<string, Queue<GameObject>>();
        instance = this;
	}


    public static void pullBackBullet(GameObject bullet, string type) {
        bullet.transform.position = GameConfig.OUT_BOUND;
        bullet.SetActive(false);

        if (!instance.bulletPool.ContainsKey(type)) {
            Queue<GameObject> singlePool = new Queue<GameObject>();
            instance.bulletPool.Add(type, singlePool);
        }
        instance.bulletPool[type].Enqueue(bullet);
    }


    private static GameObject getOrCreate(GameObject prefab , string type) {
        GameObject obj = null;
        if (!instance.bulletPool.ContainsKey(NormalBullet.TYPE)
            || instance.bulletPool[NormalBullet.TYPE].Count <= 0)
        {
            obj = GameObject.Instantiate(prefab);
        }
        else {
            obj = instance.bulletPool[NormalBullet.TYPE].Dequeue();
            obj.SetActive(true);
        }
        return obj;
    }

    /// <summary>
    /// 创建一个普通的子弹
    /// </summary>
    /// <param name="kind">类型，敌机还是玩家等</param>
    /// <param name="pos">位置</param>
    /// <param name="angle">角度</param>
    /// <param name="isUp">方向</param>
    /// <param name="speed">速度</param>
    /// <returns></returns>
    public static  GameObject createNormalBullet(int kind, 
        Vector3 pos,
        float angle = 0,
        bool isUp = true ,
        float speed = 12) {

        GameObject obj = getOrCreate(instance.normalBulletPrefab, NormalBullet.TYPE);
        obj.GetComponent<Entity>().setKind(GameConfig.PLAYER);
        obj.GetComponent<Entity>().setKind(kind);
        obj.GetComponent<Entity>().type = NormalBullet.TYPE;

        obj.transform.localRotation = Quaternion.Euler(0, 0, angle);
        obj.transform.SetParent(instance.emptyRoot.transform);
        obj.transform.position = pos;
        obj.GetComponent<LineMover>().go(isUp, angle, speed);
        return obj;
    }
	
}
